<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%">
    <el-form
        ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading"
        :inline="true">
      <el-form-item label="风险类型" prop="riskType" class="w-80" >
        <el-select
            v-model="formData.riskType" placeholder="请选择风险类型" @change="refreshRiskList"
            :disabled="disableStatus">
          <el-option
              :label="value" :value="Number(key)" :key="key"
              v-for="(value, key) in riskTypeDict"/>
        </el-select>
      </el-form-item>
      <el-form-item label="风险点" prop="riskTypeInfoId" class="w-80">
        <el-select
            :disabled="disableStatus" @change="updRiskInfoName"
            v-model="formData.riskTypeInfoId"
            placeholder="请选择风险点" v-if="formData.riskType != 2">
          <el-option
              :label="item.name" :value="Number(item.id)" v-for="item in riskList"
              :key="item.id"/>
        </el-select>
        <el-select
            :disabled="disableStatus" @change="updRiskInfoName"
            v-model="formData.riskTypeInfoId"
            placeholder="请选择风险点" v-if="formData.riskType == 2">
          <el-option
              :label="item.name" :value="Number(item.id)" v-for="item in deviceList"
              :key="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item
          label="设备实例" prop="riskTypeInfoName" class="w-80"
          v-if="formData.riskType==2">
        <el-select
            :disabled="formType !== 'create'" @change="updRiskInfoName"
            v-model="formData.instanceId"
            placeholder="请选择设备实例" v-if="formData.riskType == 2">
          <el-option
              :label="item.code+'('+item.unitName+')'" :value="Number(item.id)"
              v-for="item in deviceInstances"
              :key="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item
          v-if="formData.riskType==2"
          label="样本库" prop="sample" class="w-80">
        <el-select
            :disabled="formType!== 'create'"
            @change="sampleLoad"
            v-model="formData.sample"
            placeholder="请选择样本库"
            clearable
            filterable
            remote
            :remote-method="getSampleList"
        >
          <el-option
              v-for="item in sampleList"
              :label="item.name"
              :value="Number(item.id)"
              :key="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item class="float-right">
        <el-button type="primary" @click="addRiskTarget">新增风险</el-button>
      </el-form-item> -->
      <Draggable v-model="formData.identifyTargets" :min="2">
        <template #default="{ element: item, index }">
          <div class="flex flex-col gap-2">
            <el-card class="w-full" shadow="hover">
              <template #header>
                <div class="card-header">
                  <div class="w-full justify-end flex ">
                    <el-button
                        type="text" :icon="Close" style="margin-top: -10px;margin-right: -5px"
                        @click="removeIdentifyObject(index)"/>
                  </div>
                  <div>
                    风险对象:
                    <el-input
                        v-model="item.riskTarget" placeholder="请输入风险对象"
                        style="width: 200px"/>
                    <el-button type="primary" @click="add_content(item, index)" class="float-right">
                      新增内容
                    </el-button>
                  </div>
                </div>
              </template>
              <el-table :data="item.contents" style="width: 100%">
                <el-table-column label="编码" align="center" prop="identifyContentCode">
                  <template #default="{ row }">
                    <el-input
                        disabled v-model="row.identifyContentCode"
                        placeholder="请输入辨识内容编码"/>
                  </template>
                </el-table-column>
                <el-table-column label="辨识内容" align="center" prop="identifyContent">
                  <template #default="{ row }">
                    <el-input v-model="row.identifyContent" placeholder="请输入辨识内容"/>
                  </template>
                </el-table-column>
                <el-table-column prop="hazard" label="危害">
                  <template #default="{ row }">
                    <el-input v-model="row.hazard" placeholder="请输入危害"/>
                  </template>
                </el-table-column>
                <el-table-column prop="projectSolution" label="工程解决方案">
                  <template #default="{ row }">
                    <el-input v-model="row.projectSolution" placeholder="请输入工程解决方案"/>
                  </template>
                </el-table-column>
                <el-table-column prop="managerSolution" label="管理解决方案">
                  <template #default="{ row }">
                    <el-input v-model="row.managerSolution" placeholder="请输入管理解决方案"/>
                  </template>
                </el-table-column>
                <el-table-column prop="selfSolution" label="个人解决方案">
                  <template #default="{ row }">
                    <el-input v-model="row.selfSolution" placeholder="请输入个人解决方案"/>
                  </template>
                </el-table-column>
                <el-table-column prop="trainEduSolution" label="培训教育方案">
                  <template #default="{ row }">
                    <el-input v-model="row.trainEduSolution" placeholder="请输入培训教育方案"/>
                  </template>
                </el-table-column>
                <el-table-column prop="badSolution" label="应急解决方案字段">
                  <template #default="{ row }">
                    <el-input v-model="row.badSolution" placeholder="请输入应急解决方案字段"/>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template #default="{ $index }">
                    <el-button type="primary" :icon="Delete" @click="del_content(index, $index)"/>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </template>
      </Draggable>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {RiskListApi} from '@/api/zjyj/risklist';
import {Delete, Close} from '@element-plus/icons-vue';
import {DeviceApi} from '@/api/zjyj/device';
import {RiskIdentifyApi} from '@/api/zjyj/riskidentify';
import {riskTypeBizCodePREFIXDict, riskTypeDict} from '@/utils/dict';
import pinyin from 'pinyin';
import {DeviceInstanceApi} from '@/api/zjyj/deviceinstance';
import Draggable from '@/components/Draggable/index.vue';
import {RiskSampleApi} from "@/api/zjyj/risksample";


/** 风险辨识 表单 */
defineOptions({name: 'RiskIdentifyObjectForm'});

const {t} = useI18n(); // 国际化
const message = useMessage(); // 消息弹窗

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref(''); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(''); // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  riskType: undefined,
  riskTypeInfoId: undefined,
  instanceId: undefined,
  identifyTargets: []
});
const formRules = reactive({
  riskType: [{required: true, message: '风险类型不能为空', trigger: 'change'}],
  riskTypeInfoId: [{required: true, message: '风险点不能为空', trigger: 'blur'}],
  riskTarget: [{required: true, message: '风险对象不能为空', trigger: 'blur'}],
  identifyContent: [{required: true, message: '辨识内容不能为空', trigger: 'blur'}]
});
const formRef = ref(); // 表单 Ref

const deviceList = ref([]);
const deviceInstances = ref([]);
const sampleList = ref([]);

const getSampleList = async (text: string) => {
  try {
    const res = await RiskSampleApi.getRiskSamplePage({
      pageNo: 1,
      pageSize: 9999,
      name: text // 将用户输入作为 name 参数
    });
    sampleList.value = res.list;
  } finally {
  }
};

const riskList = ref([]);
const getRiskList = async () => {
  if (!formData.value.riskType) {
    return;
  }
  if (formData.value.riskType == 2) {
    await getDeviceList();
  } else {
    await RiskListApi.getRiskListPage({
      type: formData.value.riskType,
      page: 1,
      pageSize: 9999
    }).then(res => {
      riskList.value = res.list;
    });
  }

};
const getDeviceList = async () => {
  const data = await DeviceApi.getDevicePage({page: 1, pageSize: 9999});
  deviceList.value = data.list;
};

const getDeviceInstances = async (deviceId) => {
  const res = await DeviceInstanceApi.getDeviceInstancePage({
    pageNo: 1,
    pageSize: 9999,
    deviceId: deviceId
  });
  deviceInstances.value = res.list;
};
const add_content = async (data, object_index) => {
  if (data.contents == undefined) {
    data.contents = [];
  }
  data.contents.push({
    identifyContent: '',
    identifyContentCode: contentCodeInit(formData.value.riskType, object_index, data.contents.length),
    hazard: '',
    projectSolution: '',
    managerSolution: '',
    selfSolution: '',
    trainEduSolution: '',
    badSolution: '',
  });
};
const del_content = async (object_index: number, index: number) => {
  console.log('del_content', index, formData.value?.identifyTargets[object_index]);
  formData.value?.identifyTargets[object_index].contents.splice(index, 1);
};
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true;
  dialogTitle.value = t('action.' + type);
  formType.value = type;
  resetForm();
  await getSampleList("");
  if (id) {
    formLoading.value = true;
    try {
      disableStatus.value = true;
      const identify = await RiskIdentifyApi.getRiskIdentify(id);
      formData.value.riskType = identify.riskType;
      formData.value.riskTypeInfoId = identify.riskTypeInfoId;
      await getDeviceInstances(identify.riskTypeInfoId)
      // 遍历 formData.value.identifyTargets，给每个 identifyTargets 增加一个 contents 数组
    } finally {
      formLoading.value = false;
    }
  }
  await getRiskList();
};
defineExpose({open}); // 提供 open 方法，用于打开弹窗

const sampleLoad = async (sampleId) => {
  if (sampleId == undefined) {
    return;
  }
  sampleList.value.filter(item => item.id == sampleId)
  // 遍历 sampleList.value 如果id == sampleId 返回 使用find函数
  const sample = sampleList.value.find(item => item.id == sampleId);
  if (sample == undefined) {
    return;
  }
  formData.value.identifyTargets = [];
  formData.value.identifyTargets = sample?.riskDetail
};

/** 提交表单 */
const emit = defineEmits(['success']); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value;
    if (formType.value === 'create') {
      await RiskIdentifyApi.createRiskIdentify(data);
      message.success(t('common.createSuccess'));
    } else {
      await RiskIdentifyApi.updateRiskIdentify(data);
      message.success(t('common.updateSuccess'));
    }
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit('success');
  } finally {
    formLoading.value = false;
  }
};

const disableStatus = ref(false);
const addRiskTarget = async () => {
  formData.value?.identifyTargets.push({
    id: undefined,
    riskTarget: '', contents: [{
      identifyContent: '',
      identifyContentCode: contentCodeInit(
          formData.value.riskType,
          formData.value.identifyTargets.length,
          0
      ),
      hazard: '',
      projectSolution: '',
      managerSolution: '',
      selfSolution: '',
      trainEduSolution: '',
      badSolution: '',
    }]
  });
};
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    riskType: undefined,
    riskTypeInfoId: undefined,
    identifyTargets: [],
  };
  formRef.value?.resetFields();
  disableStatus.value = false;
};



const removeIdentifyObject = async (index) => {
  await message.delConfirm();
  console.log(formData.value.identifyTargets, index)
  formData.value.identifyTargets.splice(index, 1);
};

const refreshRiskList = async () => {
  await getRiskList();
};

const riskInfoName = ref('');

const updRiskInfoName = async () => {
  if (formData.value.riskType == 2) {
    await getDeviceInstances(formData.value.riskTypeInfoId);
    deviceList.value.forEach(item => {
      if (item.id == formData.value.riskTypeInfoId) {
        riskInfoName.value = item.name;
      }
    });
  } else {
    riskList.value.forEach(item => {
      if (item.id == formData.value.riskTypeInfoId) {
        riskInfoName.value = item.name;
      }
    });
  }
};

const contentCodeInit = (riskType, objectIndex, contentSize) => {
  const prefix = riskTypeBizCodePREFIXDict[riskType];
  // riskInfoName 是中文，获取他的中文每个字拼音的首字母，大写，用_连接
  const initials = pinyin(riskInfoName.value, {
    style: pinyin.STYLE_FIRST_LETTER,
    heteronym: false
  }).map(item => item[0].toUpperCase()).join('');
  const paddedObjectIndex = String(objectIndex + 1).padStart(2, '0');
  const paddedContentSize = String(contentSize + 1).padStart(3, '0');
  return `${prefix}${initials}${paddedObjectIndex}${paddedContentSize}`;
};
</script>

<style scoped>
:deep(.el-card__header) {
  padding: 10px;
}
</style>
